package cloud.xlh.auth.service.impl;

import cloud.xlh.auth.domin.bo.UserInfoBO;
import cloud.xlh.auth.domin.dto.UserInfoDTO;
import cloud.xlh.auth.enums.CacheTypeEnum;
import cloud.xlh.auth.service.CommonService;
import cloud.xlh.auth.service.LoginService;
import cloud.xlh.auth.service.TokenService;
import cloud.xlh.auth.service.UserSecurityService;
import cloud.xlh.infrastructure.cache.operate.CacheOperateService;
import cloud.xlh.infrastructure.utils.CommonUtil;
import cloud.xlh.infrastructure.utils.JSONObjectUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/1/15 20:53
 * @ Description:
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Value("${jwt.activeTime}")
    private long activeTime;
    @Autowired
    private UserSecurityService userSecurityService;

    @Override
    public JSONObject login(UserInfoDTO userInfoDTO, HttpServletRequest request, HttpServletResponse response) {
        UserInfoBO userInfoBO = new UserInfoBO();
        CommonUtil.copyPropertiesIgnoreCase(userInfoDTO, userInfoBO);
        log.info("LoginServiceImpl->login 处理中");
        /**
         * 1.查库，验证是否存在此用户
         * */
        CommonService commonService = userSecurityService.getCommonService();
        JSONObject userInfoBOJsonObject = JSONObjectUtil.javaObjectToJSONObject(userInfoBO);
        if (commonService.verifyUser(userInfoBOJsonObject)) {

        } else {

        }
        /**
         * 2.1通过后，生成token，返回token给客户端
         * */
        TokenService tokenService = userSecurityService.getTokenService();
        String token = tokenService.generateToken(userInfoBO);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retCode", "PR00");
        jsonObject.put("retInfo", "SUCCESS");
        jsonObject.put("token", token);
        /**
            3.存caffeine再存redis
         **/
        CacheOperateService cacheOperateService = userSecurityService.getCacheOperateService(CacheTypeEnum.CAFFEINE.getCode());
        cacheOperateService.putIfNotPresentOrReturn(token, activeTime, TimeUnit.MILLISECONDS, userInfoBO);
        cacheOperateService = userSecurityService.getCacheOperateService(CacheTypeEnum.REDIS.getCode());
        cacheOperateService.putIfNotPresentOrReturn(token, activeTime, TimeUnit.MILLISECONDS, userInfoBO);
        return jsonObject;
    }
}
